<template>
  <view class="page-container">
    <view v-if="!isLogin" class="no_login_wrap">
      <image src="../../../static/img/user/no_login.png" mode="aspectFill"></image>
      <h4>需要登录才可以使用该功能哦~</h4>
      <button @tap="jumpLogin">立即登录</button>
    </view>
    <view v-else class="logined_wrap">
      <view class="form-wrapper">
        <view class="cell-column">
          <view class="title">姓名</view>
          <view class="input-wrapper">
            <input class="uni-input" maxlength="10" v-model="base.name" placeholder="请填写姓名" />
            <image class="suffix" src="../../../static/img/user/pen.png" mode="widthFix"></image>
          </view>
        </view>
        <view class="cell-column">
          <view class="title">职称</view>
          <view class="input-wrapper">
            <picker :value="jobIndex" :range="jobArray" @change="bindPickerChange">
              <view class="uni-input" :class="{placeholder: jobIndex === ''}">{{jobIndex === '' ? '请选择职称' : jobArray[jobIndex]}}</view>
            </picker>
            <image class="suffix-arrow" src="../../../static/img/user/arrow.png" mode="widthFix"></image>
          </view>
        </view>
        <view class="cell-column">
          <view class="title">医院</view>
          <view class="input-wrapper hospital-wrapper" @tap="goHospital">
            <view class="uni-input ell" :class="{placeholder: !hospitalName}">{{hospitalName || '请选择医院'}}</view>
            <image class="suffix-arrow" src="../../../static/img/user/arrow.png" mode="widthFix"></image>
          </view>
        </view>
        <view class="cell-column">
          <view class="title">科室</view>
          <view class="input-wrapper">
            <picker mode="multiSelector" @change="bindMultiPickerChange" @columnchange="bindMultiPickerColumnChange"
              :value="multiIndex" :range="multiArray">
              <view class="uni-input" :class="{placeholder: departmentIndex === ''}">{{departmentIndex === '' ? '请选择科室' : multiArray[1][multiIndex[1]]}}</view>
            </picker>
            <image class="suffix-arrow" src="../../../static/img/user/arrow.png" mode="widthFix"></image>
          </view>
        </view>
      </view>

      <view class="page-footer">
		  <view style="text-align: center; width: 100vw; padding-bottom: 20rpx;" @tap="callPhone">联系客服：17769537971（微信同号）</view>
        <button class="btn-save" type="primary" @tap="btnNext">下一步</button>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    getHcp,
    getConsts,
    getDepartment,
    postAccount
  } from '@/utils/api';
  export default {
    data() {
      return {
        isLogin: false,
        base: { // 基本信息
          name: '',
          title: '', // 职称
          hospital: '',
          department: '' // 科室
        },
        hospitalName: '',
        jobDict: [],
        jobArray: [],
        jobIndex: '',
        departmentDict: [
          [],
          []
        ], // 科室
        multiArray: [],
        multiIndex: [0, 0],
        departmentIndex: '',
        userInfo: ''
      }
    },
    onShow() {
      let auth_token = uni.getStorageSync("auth_token");
      if (auth_token) {
        this.isLogin = true;
        this.departmentIndex = ''
        this.queryUser(); // 查询用户信息
      } else {
        this.isLogin = false;
      }
    },
    onBackPress() {
      uni.removeStorageSync('hospital');
      uni.removeStorageSync('userAuth');
    },
    methods: {
		callPhone(){
			uni.makePhoneCall({
			    phoneNumber: '17769537971',
				success: (res) => {
					console.log('调用成功!')	
				},
				fail: (res) => {
					console.log('调用失败!')
				}
			  });
		},
      // 查询用户信息
      async queryUser() {
        let res = await getHcp();
        let userInfo = res.data;
        console.log(userInfo)
        // console.log(JSON.parse(JSON.stringify(userInfo)))
        const userAuth = uni.getStorageSync('userAuth');
        const hospital = uni.getStorageSync('hospital')
        if (hospital) {
          userInfo.hospital = hospital.name;
          userInfo.hospitalId = hospital.id;
        }
        if (userAuth) {
          userInfo.name = userAuth.name;
          userInfo.titleValue = userAuth.title;
          userInfo.departmentId = userAuth.department;
        }
        this.userInfo = userInfo;
        // 回显基本信息
        this.base.name = userInfo.name || '';
        this.hospitalName = userInfo.hospital ? userInfo.hospital : '';
        this.base.hospital = userInfo.hospitalId ? userInfo.hospitalId : '';

        this.queryJob(); // 查询职称字典项
        this.queryDepartment(); // 查询科室字典项

        // uni.setStorageSync("userInfo", res.data);
      },
      // 查询职称字典项
      async queryJob() {
        let res = await getConsts('HcpTitle');
        this.jobDict = res.data || [];
        this.jobArray = this.jobDict.map(item => item.label)
        // 回显职称
        let userInfo = this.userInfo;
        // console.log(this.userInfo)
        if (userInfo && userInfo.titleValue) {
          this.jobDict.forEach((item, index) => {
            if (item.value == userInfo.titleValue) {
              this.jobIndex = index
              this.base.title = item.value
            }
          })
        }
      },
      // 查询科室字典项
      async queryDepartment() {
        let res = await getDepartment();
        this.departmentDict = res.data || [];

        // 组合pick数据格式
        let column1 = [];
        this.departmentDict.forEach(item => {
          column1.push(item.label)
        })
        let children = this.departmentDict[0].children || []
        let column2 = children.map(item => item.label)

        this.multiArray = [column1, column2]

        // 回显科室
        let userInfo = this.userInfo;

        if (userInfo && userInfo.departmentId) {
          let len = this.departmentDict.length
          for (let i = 0; i < len; i++) {
            let children = this.departmentDict[i].children;
            let col2 = []
            for (let j = 0; j < children.length; j++) {
              col2.push(children[j].label)
              if (children[j].id === userInfo.departmentId) {
                this.multiIndex = [i, j];
                this.departmentIndex = [i, j];
              }
            }
            if (this.departmentIndex !== '') {
              this.multiArray[1] = col2;
              this.base.department = this.departmentDict[this.multiIndex[0]].children[this.multiIndex[1]].id;
              break;
            }
          }
        }
      },
      bindPickerChange(e) {
        let value = e.target.value
        this.jobIndex = value
        // 保存职称id值
        this.base.title = this.jobDict[value].value
      },
      bindMultiPickerColumnChange(e) {
        let column = e.detail.column
        let value = e.detail.value
        this.multiIndex[column] = value
        if (column === 0) {
          let children = this.departmentDict[value].children || []
          this.multiArray[1] = children.map(item => item.label)
        }
        this.$forceUpdate()
      },
      bindMultiPickerChange(e) {
        let value = e.target.value
        this.departmentIndex = value
        let children = this.departmentDict[this.multiIndex[0]].children
        this.base.department = children[this.multiIndex[1]].id
      },
      // 跳转到登录页面
      jumpLogin() {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      },
      // 跳转到医院搜索页面
      goHospital() {
        uni.setStorageSync('userAuth', this.base);
        uni.navigateTo({
          url: '/pages/user/info/hospital'
        })
      },
      // 验证
      validate() {
        if (this.base.name === '') {
          uni.showToast({
            title: '请填写姓名',
            icon: 'none'
          });
          return false;
        }
        if (this.base.title === '') {
          uni.showToast({
            title: '请选择职称',
            icon: 'none'
          });
          return false;
        }
        if (!this.base.hospital) {
          uni.showToast({
            title: '请选择医院',
            icon: 'none'
          });
          return false;
        }
        if (!this.base.department) {
          uni.showToast({
            title: '请选择科室',
            icon: 'none'
          });
          return false;
        }
        return true;
      },
      // 下一步
      async btnNext() {
        if (!this.validate()) {
          return
        }
        console.log(this.base)
        const res = await postAccount(this.base);
        if (res.status === 0) {
          uni.removeStorageSync('hospital');
          uni.removeStorageSync('userAuth');
          uni.removeStorageSync('auth_physicianLicense');
          uni.removeStorageSync('auth_workPermit');
          uni.removeStorageSync('auth_idCard');
          uni.removeStorageSync('auth_halfLength');
          uni.removeStorageSync('identities');
          uni.navigateTo({
            url: '/pages/user/info/authentication'
          })
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none',
            duration: 2000
          });
        }
        // uni.setStorageSync('userAuth', this.base);
        // uni.navigateTo({
        //   url: '/pages/user/info/authentication'
        // })
      }
    }
  }
</script>

<style>
  @import url("../../../static/style/no_login.css");
  @import url("../../../static/style/user.css");

  page {
    background: #F4F4F4;
  }

  .page-container {
    height: 100%;
  }

  .logined_wrap {
    display: flex;
    height: 100%;
    flex-direction: column;
    justify-content: space-between;
  }

  .form-wrapper {
    background: #FFFFFF;
  }

  .cell-column {
    height: 108upx;
    border-bottom: 2upx solid #F4F4F4;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30upx;
  }

  .title {
    font-size: 30upx;
    color: #999;
    min-width: 100upx;
  }

  .input-wrapper {
    display: flex;
    align-items: center;
  }

  .hospital-wrapper {
    min-width: 0;
  }

  .uni-input {
    text-align: right;
    font-size: 30upx;
    color: #333;
    padding-right: 10upx;
  }

  .uni-input.placeholder {
    color: grey;
  }

  .ell {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .suffix {
    width: 40upx;
    height: 40upx;
  }

  .suffix-arrow {
    margin-left: 16upx;
    width: 24upx;
    height: 44upx;
  }
</style>
